package com.hung.trade.coupon.mq.processer;

import com.alibaba.fastjson.JSON;
import com.hung.trade.common.constants.TradeEnums;
import com.hung.trade.common.protocol.OrderCancelMessage;
import com.hung.trade.common.protocol.coupon.ChangeCouponReq;
import com.hung.trade.common.protocol.coupon.ChangeCouponResp;
import com.hung.trade.common.rocketmq.IMessageProcesser;
import com.hung.trade.coupon.service.ICouponService;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.UnsupportedEncodingException;

/**
 * @author hungki
 * @createTime 2018-10-09 下午 2:18
 */
public class CouponOrderCancelProcesser implements IMessageProcesser {
    private static final Logger logger = LoggerFactory.getLogger(CouponOrderCancelProcesser.class);
    @Autowired
    private ICouponService iCouponService;
    @Override
    public boolean heandlerMessage(MessageExt messageExt) {
        try {
            String body =new String(messageExt.getBody(),"UTF-8");
            String topic = messageExt.getTopic();
            String msgId = messageExt.getMsgId();
            String keys = messageExt.getKeys();
            String tags = messageExt.getTags();
            logger.info(String.format("recive message [ body = %s ] ",body));

            OrderCancelMessage orderCancelMessage = JSON.parseObject(body,OrderCancelMessage.class);
            if(orderCancelMessage.getCouponId()!=null ){
                ChangeCouponReq changeCouponReq = new ChangeCouponReq();
                changeCouponReq.setCouponId(orderCancelMessage.getCouponId());
                changeCouponReq.setOrderId(orderCancelMessage.getOrderId());
                changeCouponReq.setUserId(orderCancelMessage.getUserId());
                changeCouponReq.setIsUsed(TradeEnums.YesNoEnum.NO.getCode());

                ChangeCouponResp changeCouponResp = iCouponService.changeCoupon(changeCouponReq);

                System.out.println("changeCouponResp = " + changeCouponResp);
                if(null == changeCouponResp||changeCouponResp.getRetCode().equals(TradeEnums.RetEnum.FAIL.getCode())){
                    return false;
                }else{
                    return true;
                }
            }

        } catch (UnsupportedEncodingException e) {
            return false;
        }
        return false;
    }
}
